import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {User} from "../models/user.model";

@Injectable({
  providedIn: "root"
})
export class AuthService{
  private url = "https://localhost:44328/api/user/login";
  private tokenKey = 'auth_token';
  private userKey: string = "auth_user";
  public user: User | undefined;

  constructor(private http: HttpClient) {
    let intoken = localStorage.getItem(this.tokenKey);
    let inuser = localStorage.getItem(this.userKey);
    if(intoken!=null) this.token = intoken;
    if(inuser!=null) this.user = JSON.parse(inuser);
  }

  // private username: string | undefined;
  public token: string | undefined;

  login(username: string, password: string){
    const body = {
      username: username,
      password: password
    };
    return this.http.post<any>(this.url,body)
      .subscribe(response => {
        this.restore({name: username,id: response.id}, response.token);
      });
  }

  restore(user: User, token: string){
    this.user = user;
    this.token = token;
    localStorage.setItem(this.tokenKey, token);
    localStorage.setItem(this.userKey, JSON.stringify(this.user));
  }

  logout(){
    this.token = undefined;
    this.user = undefined;
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.userKey);
  }

  getIsLoggedIn(): boolean{
    return !!this.token;
  }

  getUsername() {
    return this.user?.name;
  }
}
